package com.mes.scheduler.task;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

import com.mes.scheduler.pool.ThreadPoolUtil;
import com.mes.utils.DBConctionQuery;

public class TaskScheduler {
	private static ThreadPoolUtil util = null;
	static {
		util = new ThreadPoolUtil(10, 50, 5, TimeUnit.MINUTES, new ArrayBlockingQueue<Runnable>(5));
	}
	
	public void run() {
//		System.out.println("调度执行----------------"+new Date().getTime());
		DBConctionQuery query = new DBConctionQuery();
		try {
			List<Map<String, Object>> list = this.getTaskSchedulerList(query);
			if (list != null && !list.isEmpty()) {
				for (int i = 0; i < list.size(); i++) {
					//更新任务状态
					this.updateTaskStatus((String)list.get(i).get("ID"), (String)list.get(i).get("NAME"), query);
					//执行任务调度
					util.execute(new SchedulerRun(list.get(i)));
				}
			}
		} finally {
			query.close();
		}
	}
	
	private List<Map<String, Object>> getTaskSchedulerList(DBConctionQuery query) {
		try {
			List<Map<String, Object>> list = query.query(
				"select Emes_Task_Scheduler_Id id, Name, Case_Sql, run_cycle, dc_point, Facilities_type,lower_val,upper_val " +
				"from Emes_Task_Scheduler ts where ts.next_run_time <= now()" +
				" and nvl(status, 'STOP') = 'STOP' and isactive='Y'");
			return list;
		} catch (Exception e) {
			System.out.println("查询任务列表异常：" + e.getMessage());
			e.printStackTrace();
		} finally {
			query.close();
		}
		return null;
	}
	
	private void updateTaskStatus(String id, String name, DBConctionQuery query) {
		try {
			String sql = "update Emes_Task_Scheduler set status = 'RUNNING', Last_Run_Time = now() where Emes_Task_Scheduler_Id = ?";
			query.execute(sql, id);
		} catch (Exception e) {
			System.out.println(name + "更新任务状态失败");
			e.printStackTrace();
		}
	}
}